package cn.cdiothree.service.impl;

import cn.cdiothree.dao.OrderRatingMapper;
import cn.cdiothree.dataobject.OrderRating;
import cn.cdiothree.enums.ResultEnum;
import cn.cdiothree.exception.SellException;
import cn.cdiothree.service.OrderRatingService;
import cn.cdiothree.util.KeyUtil;
import cn.cdiothree.vo.ResultVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 用户评分服务类
 * @author cumthing
 */
@Service
@Slf4j
public class OrderRatingServiceImpl extends ServiceImpl<OrderRatingMapper, OrderRating>implements OrderRatingService {

    @Autowired
    private OrderRatingMapper orderRatingMapper;

    /**
     * 添加订单评分
     * @param orderId
     * @param userId
     * @param ratingExpress
     * @param ratingQuality
     * @param ratingService
     * @return
     */
    @Override
    public ResultVo addRating(String orderId, Integer userId, Integer ratingExpress, Integer ratingQuality, Integer ratingService) {

        OrderRating aOrderRating = selectByOrderIdAndUserId(orderId, userId);
        if (aOrderRating == null) {
            OrderRating orderRating = new OrderRating();
            orderRating.setRatingId(KeyUtil.genUniqueKey());
            orderRating.setUserId(userId);
            orderRating.setOrderId(orderId);
            orderRating.setRatingExpress(ratingExpress);
            orderRating.setRatingQuality(ratingQuality);
            orderRating.setRatingService(ratingService);
            orderRating.setCreateTime(LocalDateTime.now());
            orderRating.setUpdateTime(LocalDateTime.now());
            log.info("用户{}进行评分操作，物流评分为{}分，质量评分为{}分，服务评分为{}分",userId,ratingExpress,ratingQuality,ratingService);
            int insert = orderRatingMapper.insert(orderRating);
            if (insert < 1) {
                throw new SellException(ResultEnum.RATING_FAILED);
            }
            return ResultVo.success("评分成功啦");
        } else {
            return ResultVo.success("你已经评分过啦！");
        }
    }

    /**
     * 查询订单评分
     * @param orderId
     * @param userId
     * @return
     */
    @Override
    public OrderRating selectByOrderIdAndUserId(String orderId, Integer userId){
        log.info("用户id{}，订单id{}",userId,orderId);
        QueryWrapper<OrderRating> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_id",orderId).eq("user_id",userId);
        return orderRatingMapper.selectOne(queryWrapper);
    }
}